/**
 * 
 */
package com.feib.stms.security.web.authentication;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import com.feib.stms.model.User;
import com.feib.stms.model.UserLoginControl;
import com.feib.stms.model.UserLoginHistory;
import com.feib.stms.security.core.userdetails.StmsUserDetailsWrapper;
import com.feib.stms.service.UserLoginControlService;
import com.feib.stms.service.UserLoginHistoryService;
import com.feib.stms.service.UserService;


/**
 * @author Jimmy Liu
 *
 */
public class StmsAuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler 
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private UserLoginHistoryService userLoginHistoryService;
    
    private UserLoginControlService userLoginControlService;
    
    private UserService userService;
    
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
		
		if (logger.isDebugEnabled()) {
            logger.debug( "使用者登入成功事件處理...");
        }
		
		try {
			// log 登入資訊
			Date loginTime = new Date();
			
			StmsUserDetailsWrapper principal = (StmsUserDetailsWrapper) authentication.getPrincipal();
			WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();
			
			User user = principal.getUser();
			
			UserLoginHistory userLoginHistory = new UserLoginHistory();
                        
            userLoginHistory.setUser(user);
            userLoginHistory.setUserPwd((String)authentication.getCredentials());
            // 儲存畫面的驗證碼
            userLoginHistory.setCaptch(request.getParameter("j_captcha_response"));
            userLoginHistory.setSessionId(details.getSessionId());
            userLoginHistory.setLoginTime(loginTime);
            userLoginHistory.setLoginLocaleIP(details.getRemoteAddress());
            userLoginHistory.setSucceed(Boolean.TRUE); // 成功

            userLoginHistoryService.addUserLoginHistory(userLoginHistory);
            
            // 更新使用者登入資料 UserLoginControl.
            // UserLoginControl 於 密碼檢核後的 StpsPostAuthenticationChecks 就會載入(若資料庫無資料，則會new一個新的)
            UserLoginControl userLoginControl = principal.getUser().getUserLoginControl();
            userLoginControl.setSessionId(details.getSessionId());
            userLoginControl.setLoginTime(loginTime);
            userLoginControl.setLoginLocaleIP(details.getRemoteAddress());
            userLoginControl.setActived(Boolean.TRUE);
            userLoginControl.setActivityTime(loginTime);
            userLoginControlService.saveUserLoginControl(userLoginControl);
            
            // 更新使用者主檔資訊
            userService.loginSuccess(user);
            
			
		} catch (Exception e) {
			logger.warn("使用者登入成功，新增使用者登入資訊發生錯誤！", e);
		}
		
		super.onAuthenticationSuccess(request, response, authentication);
	}

	/**
	 * @param userLoginHistoryService 的設定的 userLoginHistoryService
	 */
	public void setUserLoginHistoryService(
			UserLoginHistoryService userLoginHistoryService) {
		this.userLoginHistoryService = userLoginHistoryService;
	}

	/**
	 * @param userLoginControlService 的設定的 userLoginControlService
	 */
	public void setUserLoginControlService(
			UserLoginControlService userLoginControlService) {
		this.userLoginControlService = userLoginControlService;
	}

	/**
	 * @param userService 的設定的 userService
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
